package mspbots.autotask.data.core.contractexclusionsetexcludedworktypes;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractExclusionSetExcludedWorkTypesReceiver {
    private final ContractExclusionSetExcludedWorkTypesRepository contractExclusionSetExcludedWorkTypesRepository;

//    @RabbitListener(queues = "auto-task.contract-exclusion-set-excluded-work-types.sync")
    public void syncTask(ResultMsg content) {

        ContractExclusionSetExcludedWorkType contractExclusionSetExcludedWorkType = ContractExclusionSetExcludedWorkType.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(contractExclusionSetExcludedWorkType.getOtherId())){
            return;
        }

        this.contractExclusionSetExcludedWorkTypesRepository.findByOtherIdAndTenantId(content.getId(),content.getTenantId())
                .map(oldAdditionalInvoiceFieldValue -> {
                    contractExclusionSetExcludedWorkType.setId(oldAdditionalInvoiceFieldValue.getId());
                    return contractExclusionSetExcludedWorkType;
                })
                .defaultIfEmpty(contractExclusionSetExcludedWorkType)
                .flatMap(this.contractExclusionSetExcludedWorkTypesRepository::save).block(Duration.ofSeconds(10));

    }
}
